<?php

namespace Yearnfar\Bundle\CmsBundle\Controller;

use Doctrine\ORM\Tools\Pagination\Paginator;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Yearnfar\Bundle\CmsBundle\Entity\groups;

/**
 * @Route("/groups")
 * @Template()
 */
class GroupsController extends BaseController
{
    /**
     * @Route("/")
     */
    public function indexAction()
    {
        $request = $this->get('request');

        $rows = max(1, $request->get('rows', 10));
        $page = max(1, $request->get('page', 1));

        $em = $this->getDoctrine()->getManager();
        $cq = $em
            ->createQuery("SELECT g FROM CmsBundle:groups g")
            ->setFirstResult(($page-1) * $rows)
            ->setMaxResults($rows);

        $records = count(new Paginator($cq, true));
        $groups  = $cq->getArrayResult();

        return [
            'records'=> $records,
            'groups' => $groups,
            'page'   => $page,
            'total'   => ceil($records/$rows),
        ];
    }


    /**
     * @Route("/edit")
     */
    public function editAction()
    {
        $request = $this->get('request');
        $submit  = $request->get('submit');
        $gid     = $request->get('gid', 0);

        $em = $this->getDoctrine()->getManager();
        $current = $gid>0 ? $em->find('CmsBundle:groups', $gid) : new groups();

        if ($submit) {
            $name = $request->get('name');
            $role = $request->get('role');
            $privilege = (int)$request->get('privilege');

            $current
                ->setName($name)
                ->setRole($role)
                ->setPrivilege($privilege);

            $em->persist($current);
            $em->flush();

            if ($gid>0) {
                return $this->msgOut('修改用户分组成功!', '/groups/');
            }

            return $this->msgOut('添加用户分组成功！', '/groups/');
        }

        return [
            'current' => $current,
        ];
    }

    /**
     * @Route("/delete")
     */
    public function deleteAction()
    {
        return [];
    }
}
